package com.juyu.miliao.authentication.controller;

import com.juyu.miliao.authentication.dao.mysql.ConfigSmsDao;
import com.juyu.miliao.authentication.dao.mysql.UserLoginDao;
import com.juyu.miliao.authentication.dao.redis.SmsSenderRedisDao;
import com.juyu.miliao.authentication.domain.UserLogin;
import com.juyu.miliao.authentication.service.VerificationCodeService;
import com.juyu.miliao.common.domain.CommonHead;
import com.juyu.miliao.common.domain.ConfigSms;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.exception.IllegalParamException;
import com.juyu.miliao.common.security.exception.WrongVerificationCodeException;
import com.juyu.miliao.common.util.SmsSender;
import com.juyu.miliao.common.util.VerifyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("verificationCode")
public class VerificationCodeController {
	@Autowired
	private VerificationCodeService verificationCodeService;
	@Autowired
	private UserLoginDao userLoginDao;
	@Resource
	private SmsSenderRedisDao smsSenderRedisDao;
	@Resource
	private ConfigSmsDao configSmsDao;

	@PostMapping("phoneNum")
	public void sendPhoneNumVerificationCode(HttpServletRequest request, String phoneNum){
		CommonHead com = VerifyUtil.verifyCommonHead(request);
		if(phoneNum == null || !phoneNum.matches("^[0-9]{11}$")){
            throw new IllegalParamException("phoneNum", "手机号格式不正确");
        }
        if(smsSenderRedisDao.isMemberBlacklist(phoneNum)){
            throw new ConsumeRuntimeException("手机号异常");
        }
		if(smsSenderRedisDao.isMember(phoneNum)){
			throw new ConsumeRuntimeException("手机号1分钟内不能重复发送短信");
		}
//		Double score = smsSenderRedisDao.scoreSmsSenderEveryDay(phoneNum);
//		if(score != null && score > 10){
//			throw new ConsumeRuntimeException("该手机号发送数量受限");
//		}
		int verificationCode =  (int)((Math.random()*9+1)*1000); //生成验证码
		verificationCodeService.sendPhoneNumVerificationCode(phoneNum, verificationCode+""); //存入redis
//		SmsSender smsSender = new SmsSender(phoneNum,"验证码：("+verificationCode+")注册验证码10分钟有效，请尽快完成验证。"); //发送短信
		SmsSender smsSender = new SmsSender(phoneNum,349694,verificationCode+""); //发送短信
		smsSender.sendSms(com,getConfigSmsSing(com));
		smsSenderRedisDao.addSmsSender(phoneNum);
//		smsSenderRedisDao.addSmsSenderByEveryDay(phoneNum);
	}


	private  String getConfigSmsSing(CommonHead com){
		List<ConfigSms> configSmsList = configSmsDao.listConfigSms();
		String sign = "";
		String huamiSign = "";
		for(ConfigSms c : configSmsList){
			if (c.getAppPackageId().equals("huami")){
				huamiSign = c.getSignId();
			}
			if(c.getAppPackageId().equals(com.getAppPackageId())){
				sign = c.getSignId();
			}
		}
		if(sign.equals(""))
			sign = huamiSign;
		return sign;
	}

	@PostMapping("phoneNumForLogin")
	@CrossOrigin
	public void sendPhoneNumForLogin(HttpServletRequest request,String phoneNum){
		CommonHead com = VerifyUtil.verifyCommonHead(request);
		if(phoneNum == null || !phoneNum.matches("^[0-9]{11}$")){
            throw new IllegalParamException("phoneNum", "手机号格式不正确");
        }
        if(smsSenderRedisDao.isMemberBlacklist(phoneNum)){
            throw new ConsumeRuntimeException("手机号异常");
        }
		if(smsSenderRedisDao.isMember(phoneNum)){
			throw new ConsumeRuntimeException("手机号1分钟内不能重复发送短信");
		}
//		Double score = smsSenderRedisDao.scoreSmsSenderEveryDay(phoneNum);
//		if(score != null && score > 10){
//			throw new ConsumeRuntimeException("该手机号发送数量受限");
//		}
		int verificationCode =  (int)((Math.random()*9+1)*1000); //生成验证码
		verificationCodeService.sendPhoneNumVerificationCode(phoneNum, verificationCode+""); //存入redis
//		SmsSender smsSender = new SmsSender(phoneNum,"验证码：("+verificationCode+")登录验证码10分钟有效，请尽快完成验证。"); //发送短信
		SmsSender smsSender = new SmsSender(phoneNum,349836,verificationCode+""); //发送短信
		smsSender.sendSms(com,getConfigSmsSing(com));
		smsSenderRedisDao.addSmsSender(phoneNum);
//		smsSenderRedisDao.addSmsSenderByEveryDay(phoneNum);
	}
	
	/**
	 * 验证 验证码是否正确
	 * 
	 * 
	 * @param phoneNum
	 * @param verificationCode
	 */
	@PostMapping("validate")
	public void validateCode(String phoneNum,String verificationCode){
		if(phoneNum == null || !phoneNum.matches("^[0-9]{11}$"))
			throw new IllegalParamException("phoneNum", "手机号格式不正确");
		//验证验证码
		if(verificationCode == null || verificationCode.equals(""))
			throw new IllegalParamException("verificationCode:","验证码不能为空");
		String verification = verificationCodeService.getVerificationCodeByPhoneNum(phoneNum);
		if(verification == null || verificationCode.equals("") || !verification.equals(verificationCode))
			throw new WrongVerificationCodeException(verificationCode);
	}
	/**
	 * 修改用户密码
	 */
	@PostMapping("reset")
	public void resetPassword(String phoneNum,String password,String verificationCode){
		if(phoneNum == null || !phoneNum.matches("^[0-9]{11}$"))
			throw new IllegalParamException("phoneNum", "手机号格式不正确");
		//验证验证码
		if(verificationCode == null || verificationCode.equals(""))
			throw new IllegalParamException("verificationCode:","验证码不能为空");
		String verification = verificationCodeService.getVerificationCodeByPhoneNum(phoneNum);
		if(verification == null || verificationCode.equals("") || !verification.equals(verificationCode))
			throw new WrongVerificationCodeException();
		//验证密码
		if(password == null)
			throw new IllegalParamException("password:","密码不能为空");
		password = password.trim();
		if (!password.matches("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$"))
			throw new IllegalParamException("password:"+"密码格式错误");
		UserLogin user = userLoginDao.getUserByName(phoneNum).orElseThrow(() -> new IllegalParamException("手机号不存在"));
		//修改用户密码
		user.setPassword(password);
		userLoginDao.updateUserLogin(user);
	}
}
